package com.example.spring.rabbitmq.util;

import cn.hutool.json.JSONUtil;
import com.example.spring.rabbitmq.enums.MQSendEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * mq工具包
 * @author zengkirk
 * @date 2023/12/7
 */
@Slf4j
@Component
public class RabbitMqUtils {
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     */
    public void sendMessage(MQSendEnum data, String message) {
        sendMessage(data.exchange, data.routing, message);
    }

    /**
     * 发送消息
     */
    public void sendMessage(String exchangeName, String routingKey, Object message) {
        log.info("RabbitMQ发送消息: 交换机：" + exchangeName + ", 路由：" + routingKey + ", 消息内容：" + JSONUtil.toJsonStr(message));
        try {
            rabbitTemplate.convertAndSend(exchangeName, routingKey, message);
            log.info("RabbitMQ 消息推送成功");
        } catch (Exception e) {
            log.warn("RabbitMQ 消息推送失败：", e);
        }
    }

}
